<?php
namespace app\erp\model;

use think\Model;
use traits\model\SoftDelete;
use app\erp\validate\SiteConfigrule;
use think\Cache;

class SiteConfigdb extends Model
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';

    protected $pk = 'site_config_id';

    protected $name = 'site_config';

    protected $type = [
        'create_time' => 'timestamp:Y-m-d',
        'delete_time' => 'timestamp:Y-m-d'
    ];
    // 自动完成时间转换
    protected $autoWriteTimestamp = true;

    protected $insert = [
        'partner_id' => PARTNER_ID,
        'site_id' => SITE_ID,
        'config_name'
    ];

    protected $update = [
        'site_id' => SITE_ID
    ];

    protected function setConfigNameAttr($value)
    {
        return strtoupper($value);
    }

    public $param = array();

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        $new_arr['partner_id'] = PARTNER_ID;
        if (! isset($new_arr['site_id'])) {
            $new_arr['site_id'] = SITE_ID;
        }
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }

    public function scopeConfigName($query, $config_name)
    {
        $query->where('config_name', 'like', '%' . $config_name . '%');
    }

    public function scopeSiteConfigId($query, $site_config_id)
    {
        $query->where('site_config_id', $site_config_id);
    }

    public function base($query)
    {
        $field = $this->getDeleteTimeField(true);
        if ($field) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->onlyTrashed();
            } else {
                $query->useSoftDelete($field);
            }
        }
        $query->where('partner_id', PARTNER_ID);
        if (isset($this->param['site_id'])) {
            if ($this->param['site_id'] == 0 || $this->param['site_id'] == '') {
                $query->where('site_id', 'null');
            } else {
                $query->where('site_id', $this->param['site_id']);
            }
        } else {
            $query->where('site_id', SITE_ID);
        }
        if (isset($this->param['config_name']) && $this->param['config_name'] != '') {
            $query->configName($this->param['config_name']);
        }
        if (isset($this->param['site_config_id']) && $this->param['site_config_id']) {
            $query->siteConfigId($this->param['site_config_id']);
        }
    }

    public function ajaxSelect()
    {
        $data['count'] = $this->ajaxCount();
        $data['data'] = $this->ajaxList();
        /*if (SITE_ID != null) {
            $this->param['site_id'] = 0;
            $master_data = $this->ajaxList();
            foreach ($master_data as $key => $val) {
                $master_data[$key]['dont_del'] = 'yes';
            }
            if ($data['data']) {
                for ($i = 0; $i < count($data['data']); $i ++) {
                    $eq_flag = 0;
                    $new_arr = array();
                    $push_flag = 0;
                    for ($j = 0; $j < count($master_data); $j ++) {
                        if ($master_data[$j]['config_name'] == $data['data'][$i]['config_name']) {
                            $master_data[$j] = $data['data'][$i];
                            $eq_flag = 1;
                        }
                    }
                    if ($eq_flag == 0) {
                        foreach ($master_data as $key => $val) {
                            if ($val['view_sort'] > $data['data'][$i]['view_sort'] && $push_flag == 0) {
                                array_push($new_arr, $data['data'][$i]);
                                $push_flag = 1;
                            }
                            array_push($new_arr, $val);
                        }
                        if ($push_flag == 0) {
                            array_push($new_arr, $data['data'][$i]);
                            $push_flag = 1;
                        }
                        $master_data = $new_arr;
                    }
                }
            }
            // 重做排序
            $data['data'] = $master_data;
        }*/
        return $data;
    }

    public function ajaxCount()
    {
        $data = $this->cache($this->cache_name('site_config_count'), 86400, 'site_config')
            ->count();
        return $data;
    }

    public function ajaxList()
    {
        $data = $this->order('view_sort asc,site_config_id desc')
            ->cache($this->cache_name('site_config_list'), 86400, 'site_config')
            ->select();
        if ($data) {
            $data = $data->toArray();
            foreach ($data as $key => $val) {
                $data[$key] = $this->handleData($val);
            }
        }
        return $data;
    }

    public function ajaxFind()
    {
        $data = $this->useGlobalScope(false)
            ->where('site_config_id', $this->param['site_config_id'])
            ->master()
            ->find();
        if ($data) {
            $data = $data->toArray();
        } else {
            $data = array(
                'config_value' => ''
            );
        }
        return $data;
    }

    public function getValue()
    {
        $value = $this->field('config_value')->find();
        if ($value) {
            $value = $value->toArray();
            return $value['config_value'];
        } else {
            $value = $this->useGlobalScope(false)
                ->where('site_id', null)
                ->where('config_name', $this->param['config_name'])
                ->field('config_value')
                ->find();
            if ($value) {
                $value = $value->toArray();
                return $value['config_value'];
            } else {
                return '';
            }
        }
    }

    public function ajaxSave()
    {
        $rule = new SiteConfigrule();
        $this->param['partner_id'] = PARTNER_ID;
        $this->param['site_id'] = SITE_ID;
        if (isset($this->param['site_config_id']) && $this->param['site_config_id'] != '') {
            $get_post_config_info = $this->useGlobalScope(false)
                ->master()
                ->where('site_config_id', $this->param['site_config_id'])
                ->find()
                ->toArray();
            // 分站或主站有数据
            $chk_site_config_id = $this->useGlobalScope(false)
                ->master()
                ->where('site_id', SITE_ID)
                ->where('site_config_id', $this->param['site_config_id'])
                ->find();
            if (! $chk_site_config_id) {
                // 分站没有数据
                unset($this->param['site_config_id']);
                $get_post_config_info['config_value'] = $this->param['config_value'];
                unset($get_post_config_info['site_config_id']);
                $get_post_config_info['site_id'] = SITE_ID;
                $this->param = $get_post_config_info;
                if (! $rule->check($this->param)) {
                    return $rule->getError();
                }
                unset($this->param['partner_id']);
                unset($this->param['site_id']);
                $this->allowField(true)->save($this->param);
            } else {
                if (! $rule->scene('edit')->check($this->param)) {
                    return $rule->getError();
                }
                unset($this->param['partner_id']);
                unset($this->param['site_id']);
                $this->save($this->param, [
                    'site_config_id' => $this->param['site_config_id']
                ]);
            }
        } else {
            // 分站主站都没数据
            if (! $rule->check($this->param)) {
                return $rule->getError();
            }
            unset($this->param['partner_id']);
            unset($this->param['site_id']);
            $this->allowField(true)->save($this->param);
        }
        Cache::clear('site_config');
        return 'success';
    }
    // 软删除
    public function ajaxDelete()
    {
        if (isset($this->param['site_config_id'])) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->destroy(function ($query) {
                    $query->where('site_config_id', 'IN', $this->param['site_config_id']);
                }, true);
            } else {
                $this->destroy(function ($query) {
                    $query->where('site_config_id', 'IN', $this->param['site_config_id']);
                }, true);
            }
            Cache::clear('site_config');
            return 'success';
        }
    }

    protected function handleData($val)
    {
        foreach ($val as $k => $v) {
            $val[$k] = $v;
            switch ($k) {
                case 'config_type':
                    $config_type_arr = array(
                        '1' => '单行文本',
                        '2' => '数字输入',
                        '3' => '单项选择',
                        '4' => '多行文本'
                    );
                    $val['config_type_text'] = $config_type_arr[$v];
                    break;
                case 'config_option':
                    if ($v) {
                        $str = htmlspecialchars_decode(str_replace(chr(10), ';', $v));
                        $val['config_option_arr'] = explode(';', $str);
                    }
                    break;
                default:
                    break;
            }
        }
        return $val;
    }
}